package com.stylefeng.guns.rest.common.aop;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.cache.CacheKit;
import com.stylefeng.guns.core.support.HttpKit;
import com.stylefeng.guns.rest.Tools.CodeMsg;
import com.stylefeng.guns.rest.Tools.Result;
import com.stylefeng.guns.rest.common.persistence.model.DriverInf;
import com.stylefeng.guns.rest.modular.auth.util.IpUtil;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.auth.validator.IDriverInfService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * Created by 张亚林 on 2018/11/16.
 * 单点登录拦截器
 */
@Aspect
@Configuration
@Slf4j
public class SSOAopHandler {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private IDriverInfService driverInfService;

    private static  final String TRANSFERCACHE="CONSTANT";

    @Pointcut(value = "@annotation(com.stylefeng.guns.rest.common.annotion.SSO)")
    public void excudeService() {}

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        //获取拦截的方法名
        Signature sig = pjp.getSignature();
        MethodSignature msig = null;
        if (!(sig instanceof MethodSignature)) {
            throw new IllegalArgumentException("该注解只能用于方法");
        }
        msig = (MethodSignature) sig;
        Object target = pjp.getTarget();
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        String methodName = currentMethod.getName();

        // 获取HTTP请求头信息
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String ipAddr = IpUtil.getIpAddr(request);
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String  token=this.getToken();
        String username= jwtTokenUtil.getUsernameFromToken(token);
        if(username!=null){
            DriverInf newU = new DriverInf();
            newU.setDiPhone(username);
            DriverInf driverInf=this.driverInfService.selectOne(new EntityWrapper<>(newU));
            if(driverInf!=null){
                String otoken=  CacheKit.get(TRANSFERCACHE,"token_"+username);
                if (!StringUtils.equals(token,otoken)) {
                    log.info("IP地址:"+ipAddr+",方法名:"+methodName+",用户:"+username+",uri:"+uri+",url:"+url+",method:"+method);
                    return Result.error("TOKEN已失效",400);
                }
            }else{
                //用户不存在或被删除
                return Result.error(CodeMsg.USER_NOT_EXSIST.getMessage(),CodeMsg.USER_NOT_EXSIST.getRetCode());
            }

        }
        return pjp.proceed();
    }
    private String getToken(){
        return HttpKit.getRequest().getHeader("Authorization").substring(7);
    }
}
